<?php
/**
 * @version 	$Id: fResponse.class.php 74 2010-03-17 06:48:21Z mylifeisskidrow@gmail.com $
 * @author 		$Author: mylifeisskidrow@gmail.com $
 * @copyright 	Copyright (c) 2010 Luu Trong Hieu. All right reserved.
 * @license 	GNU/GPL see license.php
 */

defined('IN_FLYWHEEL') or die('Restricted Access');

/**
 * Response 
 * 
 * @package 	system
 * @subpackage 	environment
 *
 */

class fResponse {
	private $body;
	private $headers = array();	
	
	public function __construct() {}
	
	public function setHeader($name, $value, $replace = false) {
		$name = preg_replace('/\-(.)/e', "'-'.strtoupper('\\1')", strtr(ucfirst(strtolower($name)), '_', '-'));
		if ($value == null) {
			unset($this->headers[$name]);
			return;		
		}
		
		if (!$replace) {
			$$value = (isset($this->headers[$name])? $this->headers[$name] .', ':'') . $value;			
		}
		
		$this->headers[$name] = $value;
		
	}
	
	/**
	 * Set Response Body
	 *
	 * @param string $s
	 */
	public function setBody($s) {
		$this->body = $s;		
	}
	
	/**
	 * Send HTTP Headers
	 * 
	 * @return void
	 */
	public function sendHttpHeaders() {
		if (headers_sent())	return;
		
		if (substr(php_sapi_name(), 0, 3) == 'cgi')
	    {
	      // fastcgi servers cannot send this status information because it was sent by them already due to the HTT/1.0 line
	      // so we can safely unset them. see ticket #3191
	      unset($this->headers['Status']);
	    }
	    
	    foreach ($this->headers as $name => $value) {
	    	header($name .':' . $value);
	    }
	}
	
	/**
	* check, whether client supports compressed data
	*
	* @access	private
	* @return	boolean
	*/
	function getClientEncoding()
	{
		if (!isset($_SERVER['HTTP_ACCEPT_ENCODING'])) {
			return false;
		}

		$encoding = false;

		if (false !== strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) {
			$encoding = 'gzip';
		}

		if (false !== strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'x-gzip')) {
			$encoding = 'x-gzip';
		}

		return $encoding;
	}
	
	/**
	* Compress the data
	*
	* Checks the accept encoding of the browser and compresses the data before
	* sending it to the client.
	*
	* @access	public
	* @param	string		data
	* @return	string		compressed data
	*/
	private function compress() {
		$encoding = $this->getClientEncoding();
		if (!$encoding || !extension_loaded('zlib') || ini_get('zlib.output_compression') 
						|| headers_sent() || connection_status() !== 0)
			return;
		$this->body = gzencode($this->body, 4);
		$this->setHeader('Content-Encoding', $encoding);
		$this->setHeader('X-Content-Encoded-By', 'Flywheel<tronghieu1012@yahoo.com>');		
	 		
	}
	
	/**
	 * Send to client
	 *
	 */
	public function send() {
		if (fConfig::get('compress') 
				&& !ini_get('zlib.output_compression') 
				&& ini_get('output_handler')!='ob_gzhandler') {
			$this->compress();		
		}		

		$this->sendHttpHeaders();
		echo $this->body;
						
	}
}